<template>
  <div>
    <el-card style="height: 75px; margin-bottom: 10px">
      <el-form inline class="form-inline">
        <el-form-item label="用户名">
          <el-input v-model="username" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="handleAdd">添加用户</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
      <el-table :data="tableData" border style="margin: 10px 0" ref="tableRef">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          prop="id"
          label="ID"
          show-overflow-tooltip
          width="100"
        />
        <el-table-column
          prop="username"
          label="用户名"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="name"
          label="昵称"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column label="角色" width="300">
          <template #="{ row }">
            <el-tag
              v-for="role in row.roleName.split(',')"
              v-show="role"
              style="margin: 0 5px 5px 0"
              >{{ role }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170" />
        <el-table-column prop="updateTime" label="更新时间" width="170" />
        <el-table-column label="操作" fixed="right" width="220" align="center">
          <template #="{ row }">
            <el-button
              type="success"
              size="small"
              @click="handleAssignRole(row)"
              >分配角色</el-button
            >
            <el-button type="primary" size="small" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-popconfirm
              width="220"
              icon="Delete"
              :title="`是否删除${row.username}？`"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 10, 15]"
        :total="total"
        layout="prev, pager, next, total, ->, sizes, jumper"
        size="small"
        background
        @change="handleChange"
      />
    </el-card>
    <el-drawer
      :title="userInfo.id ? '编辑' : '新增' + `用户`"
      v-model="drawerVisible"
      @close="drawerClosed"
    >
      <el-form
        :model="userInfo"
        ref="userInfoRef"
        :rules="rules"
        label-width="80"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" />
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="userInfo.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userInfo.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveUserInfo">保存</el-button>
          <el-button @click="drawerClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
      title="分配角色"
      v-model="roleDrawerVisible"
      @close="roleDrawerClosed"
      size="50%"
    >
      <el-form :model="roleInfo" label-width="80">
        <el-form-item label="用户名">
          <el-input v-model="roleInfo.username" disabled />
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="roleInfo.roleIdList"
            @change="handleCheckedRolesChange"
          >
            <el-checkbox
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            >
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveRoleInfo">保存</el-button>
          <el-button @click="roleDrawerClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  reqGetUserList,
  reqDeleteUser,
  reqAddUser,
  reqUpdateUser,
  reqBatchDelete,
  reqGetRoleList,
  reqAssignRole
} from '@/api/acl/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
const useUserState = useUserStore()
let username = ref('')
const tableData = ref([])
let pageNo = ref(1)
let limit = ref(10)
let total = ref(0)
const handleChange = () => {
  getUserList()
}
onMounted(() => {
  getUserList()
})
const getUserList = async () => {
  const result = await reqGetUserList(pageNo.value, limit.value, username.value)
  if (result.code === 200) {
    tableData.value = result.data.records
    total.value = result.data.total
  }
}

const search = () => {
  getUserList()
}
const reset = () => {
  username.value = ''
  getUserList()
}

const handleDelete = (id: number) => {
  reqDeleteUser(id).then((res) => {
    if (res.code === 200) {
      getUserList()
    }
  })
}
const userInfo = reactive({
  username: '',
  password: '',
  name: '',
  id: undefined
})
const userInfoRef = ref()
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
  ]
})
const handleBatchDelete = () => {
  ElMessageBox.confirm('是否批量删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = tableRef.value.getSelectionRows().map((item: any) => item.id)
    reqBatchDelete(ids).then((res) => {
      if (res.code === 200) {
        getUserList()
      }
    })
  })
}
const tableRef = ref()
const handleAdd = () => {
  Object.assign(userInfo, {
    id: undefined,
    username: '',
    password: '',
    name: ''
  })
  drawerVisible.value = true
}
const handleEdit = (row: any) => {
  Object.assign(userInfo, row)
  drawerVisible.value = true
}
// 新增、编辑用户
let drawerVisible = ref(false)
const drawerClosed = () => {
  drawerVisible.value = false
}
const saveUserInfo = () => {
  userInfoRef.value.validate((valid: any) => {
    if (!valid) return

    let api = reqAddUser
    if (userInfo.id) api = reqUpdateUser
    api(userInfo).then((res) => {
      if (res.code === 200) {
        ElMessage.success((userInfo.id ? '编辑' : '新增') + '成功')
        getUserList()
        drawerClosed()
        reloadPage(userInfo.username)
      } else {
        return ElMessage.error((userInfo.id ? '编辑' : '新增') + '失败')
      }
    })
  })
}

// 分配角色
let roleDrawerVisible = ref(false)
const roleDrawerClosed = () => {
  roleDrawerVisible.value = false
  getUserList()
}
const roleInfo = reactive<any>({
  roleIdList: [],
  id: '',
  username: ''
})
const saveRoleInfo = () => {
  reqAssignRole({ roleIdList: roleInfo.roleIdList, userId: roleInfo.id }).then(
    (res) => {
      if (res.code === 200) {
        ElMessage.success('分配角色成功')
        roleDrawerClosed()
      } else {
        return ElMessage.error('分配角色失败')
      }
    }
  )
}
const handleAssignRole = (row: any) => {
  Object.assign(roleInfo, row)
  roleDrawerVisible.value = true
  getRoleList()
}
let checkAll = ref<boolean>(false)
const roles = ref<any[]>([])
const isIndeterminate = ref<boolean>(false)
const handleCheckAllChange = (val: any) => {
  roleInfo.roleIdList = val ? roles.value.map((item: any) => item.id) : []
  isIndeterminate.value = false
}
const handleCheckedRolesChange = (value: any) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}

const getRoleList = async () => {
  const result = await reqGetRoleList(roleInfo.id)
  if (result.code === 200) {
    roles.value = result.data.allRolesList
    roleInfo.roleIdList = result.data.assignRoles.map((item: any) => item.id)

    handleCheckedRolesChange(roleInfo.roleIdList)
  }
}

const reloadPage = (username: string) => {
  if (username !== useUserState.userName) return
  location.reload()
}
</script>
<style lang="scss" scoped>
.form-inline {
  display: flex;
  justify-content: space-between;
}
</style>
